import { createPinia } from 'pinia'
import { defineStore } from 'pinia'

// 创建 pinia 实例
const pinia = createPinia()

// 安全的 JSON 解析函数
const safeJsonParse = (str, defaultValue = {}) => {
    if (!str || str === 'undefined' || str === 'null') {
        return defaultValue
    }
    try {
        return JSON.parse(str)
    } catch (error) {
        console.error('JSON 解析错误:', error)
        return defaultValue
    }
}

// 定义用户 store
export const useUserStore = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: safeJsonParse(localStorage.getItem('userInfo'))
    }),

    getters: {
        isLoggedIn: (state) => !!state.token,
        getUser: (state) => state.userInfo || {}
    },

    actions: {
        setToken(token) {
            this.token = token
            localStorage.setItem('token', token)
        },

        setUserInfo(userInfo) {
            this.userInfo = userInfo || {}
            localStorage.setItem('userInfo', JSON.stringify(userInfo || {}))
        },

        clearUser() {
            this.token = ''
            this.userInfo = {}
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
        },

        updateUserInfo(partialInfo) {
            this.userInfo = { ...this.userInfo, ...partialInfo }
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        }
    }
})

// 默认导出 pinia 实例
export default pinia